const express = require("express")
const router = express.Router()
const {Login,Register,same,update,search,searchFilter,delUser,blogManager} = require("../control/user")
const {SuccessModel,ErrorModel} = require("../model/resModel")
const {secretOrKey}=require("../config/db")
const jwt = require('jsonwebtoken');
const passport = require("passport")
const md5 = require("md5")

router.post("/login",async (req,res)=>{
  let data =await Login(req,res)
  if(data.length>0){
        //将id name avatar identity 添加到token中
        const rule={id:data[0].id,username:data[0].username,avatar:data[0].avatar,status:md5(data[0].status+"ttzxh").substring(5),realname:data[0].realname}
        //expiresIn XX秒
        jwt.sign(rule,secretOrKey,{expiresIn:3600*24*365},(err,token)=>{
          if(err){
            res.status(400)
          }else{
            res.json(new SuccessModel({
              success:true,
              token:"Bearer "+token
            },"登录成功"))
          }
          
        })
  }else{
    res.json(new ErrorModel("登录失败"))

  }
})
router.post("/del",passport.authenticate("jwt",{session:false}),async (req,res)=>{
    let {status} = req.body
    if(status!=="876ea4f21078c7d38e3b0bdc74a"){
        res.json(new ErrorModel("没权限"))
    }
    let data = await delUser(req,res)
    if(data.affectedRows>0){
        res.json(new SuccessModel(data))
    }else{
        res.json(new ErrorModel("删除失败"))
    }
})
router.get("/search",passport.authenticate("jwt",{session:false}),async (req,res)=>{
    let {status} = req.query
    if(status!=="876ea4f21078c7d38e3b0bdc74a"){
        res.json(new ErrorModel("没权限"))
    }
    let data = await search(req,res)
    if(data.length>0){
        res.json(new SuccessModel(data))
    }else{
        res.json(new ErrorModel("查找失败"))
    }
})
router.get("/searchFilter",passport.authenticate("jwt",{session:false}),async (req,res)=>{
    let data = await searchFilter(req,res)
    if(data.length>0){
        res.json(new SuccessModel(data))
    }else{
        res.json(new ErrorModel("查找失败"))
    }
})
router.get("/current",passport.authenticate("jwt",{session:false}),(req,res)=>{
  res.json(req.user)
  
})

router.post("/register",async (req,res)=>{
  let data = await same(req,res)
  if(data.length>0){
    res.json(new ErrorModel("该用户名存在"))
  }else{
    let data1=await Register(req,res)
    if(data1.affectedRows>0){
      res.json(new SuccessModel("注册成功"))
    }else{
      res.json(new ErrorModel("注册失败"))
    }
  }

})

router.post("/update",async (req,res)=>{
  let data = await update(req,res)
  if(data.affectedRows>0){
    res.json(new SuccessModel("更新成功"))
  }else{
    res.json(new ErrorModel("更新失败"))
  }
})
router.get("/manager",async (req,res)=>{
  let data = await blogManager(req,res)
  if(data.length>0){
    res.json(new SuccessModel(data))
  }else{
    res.json(new ErrorModel("查找失败"))
  }
})

module.exports=router